﻿using System.Collections.Generic;
using System.Linq;
using Fee.Orders.AuthProjectWorkflow;
using Fee.Searchers;
using Identity;
using Microsoft.EntityFrameworkCore;

namespace Fee.Stores.Ef
{
    public class AuthProjectOrderOrderStore<T> : IAuthProjectOrderStore<T> where T : FeeDbContext
    {
        protected readonly T Context;

        public AuthProjectOrderOrderStore(T context)
        {
            Context = context;
        }

        public IEnumerable<AuthProjectOrder> List(DelegateOrderSearch searcher, out int total)
        {
            var roleIds = searcher.Roles.Select(f => f.Id);
            var adminRole = Context.AdminRoleId();
            var hasAdmin = roleIds.Contains(adminRole);

            var query = from _ in Context.Set<AuthProjectOrder>()
                join
                    activity in Context.WorkActivities on _.Id equals activity.ProcessInstance.Id
                where (
                      
                      (searcher.Status == null || searcher.Status == _.Status)
                      && (
                          activity.DepositUser.Id == searcher.UserId || hasAdmin
                      ))
                select _.Id;
            total = query.Distinct().Count();
            return Context.Set<AuthProjectOrder>()
              
              
                .Include(f => f.User).Skip(searcher.GetSkip()).Take(searcher.GetTake()).Where(f => query.Contains(f.Id))
                .Select(f => f);
        }

        public AuthProjectOrder GetById(int id)
        {

            IQueryable<AuthProjectOrder> result = Context.Set<AuthProjectOrder>()
                    .Include(f => f.CostDetails)
                 
                  
                    .Include(f => f.User)
                    .Include(f => f.WorkProcess).ThenInclude(f => f.Items).ThenInclude(f => f.Role)
                ;



            return result.FirstOrDefault(_ => _.Id == id);

        }
    }
}